﻿var Proxy = {
    CommunicateException: null, // 上次的异常消息。
    GetInstance: function (interfaces) {
        return new function () {
            var self = this;
            this.Interfaces = interfaces;
            this.ExceptionCallback = null; // 异常处理回调函数。
            this.Invoke = function (method, parameters, callback) {
                var result;
                var data = { Interfaces: this.Interfaces, Method: method };
                if (parameters) {
                    for (var i = 0; i < parameters.length; i++) {
                        data["Parameters" + i] = $.toJSON(parameters[i]);
                    }
                }
                $.ajax({
                    type: 'POST',
                    url: "/AjaxServiceHandler.ashx",
                    data: data,
                    async: callback != undefined,
                    success: function (rData, textStatus) {
                        eval("result=" + rData);
                        if (result && result.ExceptionType && result.Message) {
                            Proxy.CommunicateException = result;
                            if (self.ExceptionCallback)
                                self.ExceptionCallback(result)
                            else
                                throw new Error(result.Message);
                        }
                        else {
                            if (callback) callback(result);
                        }
                    }
                });
                return result;
            }
        }
    },
    Login: function (user, password) {
        return Proxy.GetInstance("").Invoke("Login", [user, password]);
    },
    Logout: function () {
        return Proxy.GetInstance("").Invoke("Logout", []);
    }
};